<template>
  <basic-container>
    <el-breadcrumb class="projectNameCrumb">
        <el-breadcrumb-item class="projectNameCrumbItem">
          <span>当前项目：</span>
          {{ projectInfo.projectName?projectInfo.projectName:'请选择项目...'}}
        </el-breadcrumb-item>
    </el-breadcrumb>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               ref="crud"
               v-model="form"
               :defaults.sync="showColumn"
               :permission="permissionList"
               :page.sync="page"
               :before-open="beforeOpen"
               @sortable-change="sortableChange"
               @row-del="rowDel"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @refresh-change="refreshChange"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @filter="filterChange"
               @sort-change="sortChange"
               @row-dblclick="handleRowDBLClick"               
               @on-load="onLoad">
      <template slot-scope="scope" slot="menu">
            <el-button type="text"
                      size="small"
                      icon="el-icon-d-arrow-right"
                      @click="enterProject(scope.row)">进入项目
            </el-button>
            <!-- <router-link to="/general/project/index">进入项目</router-link> -->
      </template>
      <template slot-scope="scope" slot="menuLeft">
            <!-- <el-button type="primary"
                      size="small"
                      v-if="permission.general_file_edit"
                      @click.stop="openBatchAddDialog">上传
                      <i class="el-icon-upload el-icon--right"></i>
            </el-button> -->
        <el-row>
          <el-col :span="10">
            <el-select size="small" v-model="projectOwner"   @change="handleMyProjectCommand"  placeholder="请选择所属">
              <el-option label="我的项目" sel value="my"></el-option>
              <el-option label="所有项目" value="all"></el-option>
            </el-select>
          </el-col>
          <el-col :span="1">
          </el-col>
          <el-col :span="10">
            <el-select size="small" v-model="projectStatus" @change="handleStatusCommand" placeholder="请选择状态">
              <el-option
                label="全部"
                value="0">
              </el-option>
              <el-option
                v-for="item in dicData.projectStatus" 
                :key="item.label"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-col>
        </el-row>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>

import {querySysMenuTreeByUserIdAndProject} from '@/api/system/sysMenuApi.js'
import {exportGeneralProjectInfoExcel,saveOrUpdateGeneralProjectInfo,saveOrUpdateGeneralProjectInfoList,saveGeneralProjectInfo,saveGeneralProjectInfoList,deleteGeneralProjectInfo,queryGeneralProjectInfo,queryGeneralProjectInfoListPage,updateGeneralProjectInfo,deleteGeneralProjectInfoList} from '@/api/general/project/generalProjectInfoApi';
import {mapGetters} from 'vuex';
import { reqCommonMsg } from '@/util/reqCommonMsg';
import {filterFormat} from '@/util/util';

export default {
  data() {
    return {
      //筛选状态
      projectOwner: 'my',
      projectStatus: '',
      dicData:[],
      currentRow: {},
      importDataArea: '',
      batchAddDialog: false,
      form: {},
      openType: '',
      selectionList: [],
      loading: true, 
      showColumn: [],
      option: {
        labelPosition: 'right',
        labelSuffix: '：',
        labelWidth: 120,
        dialogTop: '50',
        indexFixed:true, 
        stripe:true,
        calcHeight: 80,
        searchShow: false,
        searchMenuSpan: 6,
        tip: false,
        border: false,
        index: false,
        selection: false,
        addBtn: false,
        viewBtn: false,
        delBtn: false,
        cancelBtn: false,
        printBtn:false,
        saveBtn: false,
        editBtn: false,
        filterBtn:false, 
        menu: true,         
        menuWidth: 80,
        dialogMenuPosition: 'center',
        dialogDirection:'rtl',
        dialogType:'dialog',
        dialogFullscreen:false,
        dialogClickModal:false,
        dialogWidth: '70%',
        highlightCurrentRow:  true,
        column: [
          {
            label: '项目编号',
            prop: 'projectNo', 
            type: 'input', 
            search: true,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            width:150,
            overHidden: true,
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '项目名称',
            prop: 'projectName', 
            type: 'input', 
            search: true,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            overHidden: true,
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '主办部门',
            prop: 'mainDeptName', 
            type: 'tree', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            overHidden: true,
            width:200,
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '主办科室',
            prop: 'mainOfficeName', 
            type: 'tree', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            overHidden: true,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            props: {
              label: 'orgName',
              value: 'orgNo'
            },
            dicData:[]
          },
          {
            label: '优先等级',
            prop: 'priorLevel', 
            type: 'select', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            overHidden: true,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[
              {
                label:'高',
                name:'高'
              },
              {
                label:'中',
                name:'中'
              },
              {
                label:'低',
                name:'低'
              }
            ]
          },
          {
            label: '项目状态',
            prop: 'projectStatus', 
            type: 'select', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            overHidden: true,
            width:100,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '计划开始日期',
            prop: 'planBeginDate', 
            type: 'date', 
            format:'yyyy-MM-dd',
            valueFormat: 'yyyy-MM-dd',
            width:160,
            pickerOptions: {
              disabledDate(time) {
                return time.getTime() > Date.now();
              }
            },
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            overHidden: true,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '计划完成日期',
            prop: 'planFinishDate', 
            type: 'date', 
            format:'yyyy-MM-dd',
            valueFormat: 'yyyy-MM-dd',
            width:160,
            pickerOptions: {
              disabledDate(time) {
                return time.getTime() > Date.now();
              }
            },
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            overHidden: true,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          }
        ]
      },
      data: [],
      // 请求参数区
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      reqParams: {
        singleBody: {},
        listBody: [{}],
        sqlCondition:[],
        orderRule: {},
        currentPage: 1,
        pageSize: 10
      },
      commonData: null,
      conditions: [],
      orderRules: [],
      singleBody: {}
    };
  },
  
  computed: {
    ...mapGetters(['website','userInfo','orgTree','permission','menu','projectInfo']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.general_project_i_add, false),
        viewBtn: this.vaildData(this.permission.general_project_i_view, false),
        delBtn: this.vaildData(this.permission.general_project_i_delete, false),
        editBtn: this.vaildData(this.permission.general_project_i_edit, false),
        printBtn: this.vaildData(this.permission.general_project_i_print, false),
        searchBtn:this.vaildData(this.permission.general_project_i_search, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push({id : ele.id});
      });
      return ids;
    } 
  },
  methods: { 
    /**
     * 状态筛选
     */
    handleStatusCommand(commond){
      this.singleBody.projectStatus = commond;
      this.onLoad(this.page,'select');
    },
    /**
     * 我的项目筛选
     */
    handleMyProjectCommand(value){
      if(value == 'my'){ 
        this.singleBody = {
          createUserName: this.userInfo.userName
        } 
      }
      else{
        this.singleBody = {
          createUserName: ''
        }
      }
      this.onLoad(this.page,'select');
    },
    
    /**
     * 切换项目
     */
    async enterProject(row){
      var date1=new Date(); //开始时间 
      const loading = this.$loading({
        lock: true,
        text: '正在进入项目...',
        spinner: 'el-icon-loading',
      });
      //切换项目
      //1、切换菜单
      this.singleBody = {
        level: 3,
        userId: this.userInfo.userId,
        projectId: row.id
      }
      this.reqParams =  {
        singleBody: this.singleBody,
        listBody: [{}],
        currentPage: 1, 
        pageSize: this.website.maxPageSize
      }
      this.commonData = reqCommonMsg(this.reqParams)
      await querySysMenuTreeByUserIdAndProject(this.commonData).then(res => {
        const data = res.data.body.listBody;
        //获取顶部菜单索引
        let activeIndex = this.$getStore({name: this.userInfo.userId+'activeIndex'});
        //获取当前菜单
        let menus = this.$getStore({name: this.userInfo.userId+'menu'+activeIndex})
        //合并新菜单和项目菜单
        var newMenus = menus.concat(data);
        
        this.$setStore({name: this.userInfo.userId+'projectMenu'+row.id+activeIndex, content: data, type: 'session'})
        this.$store.dispatch('setMenu',newMenus);
        this.$router.$avueRouter.formatRoutes(data, true);
        
        // 保证有2秒钟的切换效果
        var date2=new Date();  //结束时间 
        var date3=date2.getTime()-date1.getTime() //时间差的毫秒数 
        if(date3 < 2000){
          setTimeout(() => {
            loading.close();
          }, (2000-date3));
        }
        else{
          loading.close();
        }
      }, error => {
        loading.close();
      });
      
      //2、跳转到项目首页
      this.$store.dispatch('setProjectInfo', row);
      this.$router.push({path: '/general/project/index'});
      window.location.reload();
    },
    /**
     * 加载列表数据
     */
    onLoad(page,option) {
      this.loading = true;
      if(!option && !this.singleBody.createUserName){
        this.singleBody.createUserName = this.userInfo.userName;
      }
      this.reqParams =  {
        singleBody: this.singleBody,
        listBody: [{}],
        sqlCondition: this.conditions,
        orderRule: this.orderRules,
        currentPage: page.currentPage, 
        pageSize: page.pageSize
      }
      this.commonData = reqCommonMsg(this.reqParams)
      queryGeneralProjectInfoListPage(this.commonData).then(res => {
        const data = res.data.body;
        this.page.total = data.total;
        this.data = data.listBody;
        this.loading = false;
        this.selectionClear();
      }, error => {
        this.loading = false; 
      });
    },
    
    /**
     * 搜索重置
     */
    searchReset() {
      this.conditions =[];
      this.singleBody = {};
      this.onLoad(this.page,'search');
    },

    /**
     * 搜索
     */
    searchChange(params, done) {
      this.singleBody = params
      this.page.currentPage = 1;
      this.onLoad(this.page,'search');
      done();
    },
    refreshChange(){
      this.onLoad(this.page,'select');
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    
    /**
     * 翻页查询
     */
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    /**
     * 更改每页条数
     */
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    /**
     * 自定义查询条件
     */
    filterChange(result) {
      this.page.currentPage = 1;
      this.conditions = filterFormat(result)
      this.onLoad(this.page);
    },
    /**
     * 列表排序
     */
    sortChange(val){
      this.orderRules=val
      this.onLoad(this.page);
    },
    /**
     * 获取业务字典参数
     */
    async getBizDict() {
      this.dicData = await this.$params.getBizDict('["projectStatus"]');
      this.findObject(this.option.column, 'projectStatus').dicData = this.dicData.projectStatus;
      this.projectStatus = this.dicData.projectStatus[1].value;
    },
  },
  created() {
    this.showColumn = this.$getStore({name:  this.userInfo.userId +'generalProjectInfoSelectorColumn'});
    //获取业务字典
    setTimeout(() => {
      this.getBizDict();
    }, 100);
  },
  watch: {
    showColumn: {
      handler(newValue, oldValue) {
        this.$setStore({name:  this.userInfo.userId+'generalProjectInfoSelectorColumn', content: this.showColumn});
      },
      deep: true
      //this.$setStore({name: this.userInfo.userId +'generalProjectInfoSelectorColumn', content: this.showColumn});
    }
  }
};
</script>
